#!/usr/bin/env bash
# @sys: centos-7 +
# @date: Fri Jul  8 15:41:59 CST 2022
# @author: yangfan
# @email: yangfan@moonpac.com
# @info: ssh_agent
# @run: ./ssh_agent.sh



# vars
target_port=( 65520 65521 65522 );
source_port=( 80    22    22    );
target_host=(
    test.local.com # test
    test.local.com # test
    test.local.com # test
);
agent_host=agent.test.com
agent_port=22
agent_pass=123
log_dir=/var/log/


# --------------------------------cannot be modified after this-------------------------------------
function check() {
    if [[ $? == 0 ]]; then
        echo -e "\033[32m${1} --------> success\033[0m";
    else
        echo -e "\033[31m${1} --------> fail\033[0m"; exit 1;
    fi
}

function isSoftware() {
    soft_name=${1}

    which ${soft_name} &>/dev/null
    if [[ $? != 0 ]]; then
        yum install ${soft_name} -y &>/dev/null
        check "yum install ${soft_name}"
    fi
}

function setPasswdFree() {
    # if you can login without passwd
    ssh agent@${agent_host} -p${agent_port} -o PreferredAuthentications=publickey -o StrictHostKeyChecking=no date &>/dev/null
    if [[ $? != 0 ]]; then
        # if install sshpass
        isSoftware sshpass

        sshpass -p${agent_pass} ssh-copy-id agent@${agent_host} &>/dev/null
        check "set passwd free"
    fi
}

function agentFun() {
    target_port=${1}
    target_host=${2}
    source_port=${3}

    # is password free
    setPasswdFree

    # if install nc
    isSoftware nc

    # if the port is active
    /usr/bin/nc -vzw3 ${agent_host} ${target_port} &>/dev/null

    if [[ $? != 0 ]]; then
        count=`ps -ef | grep '/usr/bin/ssh -fNCR' | grep ${target_port}:${target_host}:${source_port} | wc -l`

        if [[ $count < 1 ]]; then
            /usr/bin/ssh -fNCR ${target_port}:${target_host}:${source_port} -p22 agent@${agent_host}
            echo "`date` agent ${target_port}:${target_host}:${source_port} success" >> /root/restart-ssh-agent.txt
            echo -e "\033[32m`date` agent ${target_port}:${target_host}:${source_port} success\033[0m"
        else
            result=`ps -ef | grep '/usr/bin/ssh -fNCR' | grep ${target_port}:${target_host}:${source_port} | awk '{print $2}'`
            echo -e "\033[32mProcess already exists, please check agent,pid ${result}\033[0m"
        fi
    else
        echo -e "\033[32mby proxy ${target_port}:${target_host}:${source_port}\033[0m"
    fi
}

for (( i = 0; i < ${#target_port[*]}; i++ )); do
    agentFun ${target_port[i]} ${target_host[i]} ${source_port[i]}
done
